/**
 * Axios 二次封装
 * - 支持 mock 配置访问
 */

import axios from 'axios'
import config from '@/config'
import { Message } from 'element-ui'
import router from '@/router'
import { getToken } from '@/common/js/token'

const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

const service = axios.create({
  baseURL: config.baseURL,
  timeout: 8000,
})

service.interceptors.request.use((req) => {
  // TODO: token set
  let token = getToken() || config.token

  // TODO: token set
  const headers = req.headers
  if (!headers.Authorization) {
    headers.Authorization = `Bearer ${token}`
  }
  return req
})

service.interceptors.response.use((res) => {
  const { code, data, message: msg } = res.data
  if (code === '100000') return data
  if (code === 401) {
    Message.error(TOKEN_INVALID)
    setTimeout(() => {
      router.push('/login')
    }, 1500)
    return Promise.reject(TOKEN_INVALID)
  }
  Message.error(msg || NETWORK_ERROR)
  return Promise.reject(msg || NETWORK_ERROR)
})

function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }

  // 局部 mock
  let isMock = config.mock
  if (typeof options.mock != 'undefined') {
    isMock = options.mock
  }

  if (config.env === 'production') {
    service.defaults.baseURL = config.baseURL
  } else {
    service.defaults.baseURL = isMock ? config.mockURL : config.baseURL
  }

  return service(options)
}

;['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({ url, data, method: item, ...options })
  }
})

export default request
